﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using System.IO;
using System.Security.Cryptography;


namespace TCL.FUNC.QrCode.Util
{
    public class Signature
    {
        public static string GetSignatureString(X509Certificate2 cert, string text)
        {
            RSACryptoServiceProvider csp = (RSACryptoServiceProvider)cert.PrivateKey;
            SHA1Managed sha1 = new SHA1Managed();
            UnicodeEncoding encoding = new UnicodeEncoding();
            byte[] data = encoding.GetBytes(text);
            byte[] hash = sha1.ComputeHash(data);

            return System.Text.Encoding.Unicode .GetString(csp.SignHash(hash, CryptoConfig.MapNameToOID("SHA1")));
        }

        public static bool VerifySignature(X509Certificate2 cert, string text, string signature)
        {
            RSACryptoServiceProvider csp = (RSACryptoServiceProvider)cert.PublicKey.Key;
            SHA1Managed sha1 = new SHA1Managed();
            UnicodeEncoding encoding = new UnicodeEncoding();
            byte[] data = encoding.GetBytes(text);
            byte[] hash = sha1.ComputeHash(data);

            return csp.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), System.Text.Encoding.Unicode.GetBytes(signature));
        }

        public static X509Certificate2 loadPFX(string pfxFileName, string password)
        {
            X509Certificate2 _certificate = null;
            using (FileStream fs =
                       File.Open(pfxFileName, FileMode.Open))
            using (BinaryReader br = new BinaryReader(fs))
            {
                _certificate =
                    new X509Certificate2(
                       br.ReadBytes((int)br.BaseStream.Length), password, X509KeyStorageFlags.MachineKeySet |
X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
            }
            return _certificate;
        }

    }
}
